<?php

App::uses('AppController', 'Controller');

/**
 * LineSales Controller
 *
 * @property LineSale $LineSale
 */
class LineSalesController extends AppController {

    /**
     * index method
     *
     * @return void
     */
    public function index() {
        $this->LineSale->recursive = 0;
        $this->paginate = array('order' => 'LineSale.sale_id DESC');
        $this->set('lineSales', $this->paginate());
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($sale_id = null) {
        $options = array('conditions' => array('LineSale.sale_id' => $sale_id));
        $this->set('lineSales', $this->LineSale->find('all', $options));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add() {
        if ($this->request->is('post')) {
            $this->LineSale->create();
            if ($this->LineSale->save($this->request->data)) {
                $this->Session->setFlash(__('The line sale has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The line sale could not be saved. Please, try again.'));
            }
        }
        $sales = $this->LineSale->Sale->find('list');
        $promotions = $this->LineSale->Promotion->find('list');
        $this->set(compact('sales', 'promotions'));
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function edit($id = null) {
        if (!$this->LineSale->exists($id)) {
            throw new NotFoundException(__('Invalid line sale'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->LineSale->save($this->request->data)) {
                $this->Session->setFlash(__('The line sale has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The line sale could not be saved. Please, try again.'));
            }
        } else {
            $options = array('conditions' => array('LineSale.' . $this->LineSale->primaryKey => $id));
            $this->request->data = $this->LineSale->find('first', $options);
        }
        $sales = $this->LineSale->Sale->find('list');
        $promotions = $this->LineSale->Promotion->find('list');
        $this->set(compact('sales', 'promotions'));
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @throws MethodNotAllowedException
     * @param string $id
     * @return void
     */
    public function delete($id = null, $promotion_id = null, $quantityPromo = null, $shop_id = null) {
        $this->LineSale->id = $id;

        if (!$this->LineSale->exists()) {
            throw new NotFoundException(__('Invalid line sale'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->LineSale->delete() && $this->restoreStock($promotion_id, $quantityPromo, $shop_id)) {
//            $this->Session->setFlash(__('La promocion vendida,  ha sido eliminada'.$promotion_id.' - '. $quantityPromo.' - '. $shop_id));
            $this->redirect(array('controller' => 'sales', 'action' => 'index'));
        }
        $this->Session->setFlash(__('La promocion vendida, NO ha sido eliminada. Intente nuevamente'));
        $this->redirect(array('action' => 'index'));
    }

    public function deleteLine($id = null, $promotion_id = null, $quantityPromo = null, $shop_id = null) {
        $this->LineSale->id = $id;

        if (!$this->LineSale->exists()) {
            throw new NotFoundException(__('Linea No encontrada'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->LineSale->delete() && $this->restoreStock($promotion_id, $quantityPromo, $shop_id)) {
            return true;
        } else {
            return false;
        }
    }

//        Como se cancela una linea, Restauramos cantidades vendidas,
    public function restoreStock($promotion_id = null, $quantityPromo = null, $shop_id = null) {


//      listado de productos y cantidad
        $this->loadModel('ProductPromotion');
        $products = $this->ProductPromotion->find('all', array(
            'fields' => array('ProductPromotion.product_id', 'ProductPromotion.quantity'),
            'conditions' => array(
//                'ProductPromotion.shop_id' => $shop_id,
                'ProductPromotion.promotion_id' => $promotion_id))
        );


        foreach ($products as $product) {

            $idProduct = $product['ProductPromotion']['product_id'];
            $quantity = $product['ProductPromotion']['quantity'];

//        con el listado verifico stock y descuento en el Punto de Venta correspondiente
            $this->loadModel('ProductShop');
            $productShop = $this->ProductShop->find('first', array('fields' => array(
                    'ProductShop.current_stock', 'ProductShop.id',), 'conditions' => array(
                    'ProductShop.product_id' => $idProduct,
                    'ProductShop.shop_id' => $shop_id,
                    )));

            $this->ProductShop->id = $productShop['ProductShop']['id'];

            $update_stock = ($productShop['ProductShop']['current_stock'] + ($quantity * $quantityPromo ));
            $this->ProductShop->saveField('current_stock', $update_stock);
        }
        return true;
    }

}
